import pyautogui
import time
import logging
import pymysql
import socket
import pathlib
import sqlite3
import random
import pyperclip
import json
import os ,sys
from point import *
from loger import *
import platform

winver=platform.win32_ver()
root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))
log = Logger('2class',StreamLevel='debug',FileLevel='info').logger
root=pathlib.Path(__file__).parent
sqlType="mysql" #sqlite
CorrectRate=0.85
confidence=0.8
userinfo=None
if(winver[0]=="10"):
    picpath=root/"win10"
else:
    picpath=root
#error code 
    # -1 已登录
    # -2 登录失败
    # -3 登录异常
    # -4 得分记录异常
# sqlType="sqlite" 
# courseId=["1593","1594","1606","1531",'1532']
# courseId=["1591","1592","1603","1604",'1607',"1529",'1530']
# courseId=["1589","1590","1608","1527",'1528']
coursesExamsAnswer={
    "1532":[(2),(3),(0),(0),(1,0)],
    "1531":[(3),(2),(1),(3),(1)],
    "1606":[(0),(0,1,2)],
    "1594":[(0,2),(0,3)],
    "1593":[(2),(0,1,2)],
    "1591":[(0,2,3),(1,2,3)],
    "1589":[(0,1,3),(1,3)],
    "1590":[(1,2),(0,1,2,3)],
    "1608":[(0,1,2),(0,1,2,3)],
    "1527":[(2),(0),(0),(0),(1)],
    "1528":[(0,1),(2),(0,1,2,3),(0,1,2,3),(3)],
    "1592":[(2,3),(1,2)],
    "1603":[(2),(2),(3),(1,2),(0,1)],
    "1604":[(1),(1),(0,1,2)],
    "1607":[(0,1,2),(2)],
    "1529":[(0),(0),(1),(1),(0,1,2,3)],
    "1530":[(1),(0),(3),(2),(0,1,2,3)],

}



if (sqlType=="mysql"):
    hostnamelist = ['192.168.2.247',"172.16.2.174","192.168.8.247"] #example
    for i in hostnamelist:
        response = os.system(f"ping -n 1 -w 500 {i}" )
        if response == 0:
            log.info(f"connect {i}")
            try:
                db = pymysql.connect(
                    host=i
                    ,user='xjzx'
                    ,password='Af1121113'
                    ,db='2class'
                    ,charset='utf8')
            except:
                log.info(f"mysql {i} connect error!")
                exit()
            break
        else:
            print (i, 'is down!')
elif(sqlType=="sqlite"):
    db=sqlite3.connect(str(root/"2_class.db"))

cur = db.cursor()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ipaddr=(s.getsockname()[0])
log.info(ipaddr)

def LoadingCompleted(times=3,sec=15):
    while (times>0):
        times=times-1
        ss=sec
        while(ss>0):
            ss=ss-1
            p=pyautogui.locateOnScreen(str(picpath/"10.PNG"),confidence=confidence)
            if(p==None):return True
            time.sleep(1)
        pyautogui.press("F5")
    log.warning(f"页面加载失败！")
    return False


def enterUrl(url):
    if(not LoadingCompleted()):
        return False
    p=pyautogui.locateOnScreen(str(picpath/"07.PNG"),confidence=confidence)
    (x,y)=pyautogui.center(p)
    pyautogui.click(x+200,y)
    pyautogui.doubleClick()
    pyautogui.typewrite(url)
    time.sleep(0.1)
    pyautogui.press("enter")
    time.sleep(5)
def get_db(sql):
    cur.execute(sql)
    if (sqlType=="mysql"):
        return cur.fetchall()
    elif(sqlType=="sqlite"):
        r=cur.execute(sql)
        return r.fetchall()
def finda(index=0):
    if(type(index)==int):
        # log.info(pic[index])
        p=pyautogui.locateOnScreen(str(picpath/pic[index]),confidence=confidence)
    else:
        # log.info(index)
        p=pyautogui.locateOnScreen(str(picpath/index),confidence=confidence)
    return (p)
def findClick(index):
    p=finda(index)
    if(p== None):
        log.debug(f"Unable to find {index}")
        return False
    else:
        pyautogui.moveTo(pyautogui.center(p))
        time.sleep(0.5)
        pyautogui.click()
        return True
def login():
    #window.copy(window.__DATA__.userInfo.account);
    enterUrl("www.2-class.com")
    time.sleep(5)
    global userinfo
    r=get_db("SELECT * FROM class_userinfo  where classhour is null LIMIT 0, 1")
    if(r==None or r==()): 
        log.info("所有账号完成")
        exit()
        return False
    userinfo=r[0]
    # return userinfo
    cur.execute(f"UPDATE class_userinfo SET classhour=-1 WHERE (id={userinfo[0]})")
    db.commit()
    log.info(f"begin {userinfo[5]} {userinfo[1]}  {userinfo[3]}")
    findClick(0) #点击登录
    time.sleep(1)
    findClick(1) #点击用户名输入
    pyautogui.typewrite(userinfo[3])
    pyautogui.press("Tab")
    pyautogui.typewrite(userinfo[4])
    time.sleep(0.3)
    findClick(2)
    time.sleep(8)
    if(finda(3) ==None):
        if(finda("2023-10-25_160341.png")==None): #我的课程
            log.error(f"登录异常{userinfo[3]}")
            cur.execute(f"UPDATE class_userinfo SET classhour=-3 WHERE (id={userinfo[0]})")
            db.commit()
            enterUrl("https://www.2-class.com/api/user/logout")
            return False
        else:
            log.info(f"登录成功{userinfo[3]}")

            if(findClick("09.PNG")):
                time.sleep(3)
            return True
    else:
        log.error(f"登录失败{userinfo[3]}")
        cur.execute(f"UPDATE class_userinfo SET classhour=-2 WHERE (id={userinfo[0]})")
        db.commit()
        enterUrl("https://www.2-class.com/api/user/logout")
        return False
def exercises(id):
    log.info(f"begin {id}")
    answer=coursesExamsAnswer[id]
    n=0
    while (1):
        n=n+1
        if(finda("2023-10-25_161746.png")==None and finda("01.PNG")==None):
            pyautogui.click(450,500)
            pyautogui.press("F5")
            time.sleep(3*n)
            if(n>=5):
                return False
        else:
            break
    if(finda("2023-10-25_161746.png") != None):
        findClick("2023-10-25_161807.png")
        log.info("已经完成")
    else:
        findClick("01.PNG")
        time.sleep(1)
        for an in answer:
            box=[]
            if(type(an)==int):
                p=pyautogui.locateAllOnScreen(str(picpath/"03.png"),confidence=confidence)
                for i in p:
                    box.append(i)
                pyautogui.click(pyautogui.center(box[an]))
                time.sleep(0.3)
            else:
                p=pyautogui.locateAllOnScreen(str(picpath/"02.png"),confidence=confidence)
                for i in p:
                    box.append(i)
                for an_ in an:
                    pyautogui.click(pyautogui.center(box[an_]))
                    time.sleep(0.3)
            if(finda("04.PNG")==None):
                findClick("05.PNG")
                log.info(f"完成{id}")
            else:
                findClick("04.PNG")
                time.sleep(0.5)

    
def classhours(courseId):
    if(getclasshour() >2 ):
        enterUrl("https://www.2-class.com/api/user/logout")
        return False
    for id in courseId:
        rnd=random.random()
        if(rnd<=0.8):
            url=f"https://www.2-class.com/courses/exams/{id}"
            enterUrl(url)
            try:
                exercises(id)
            except:
                log.error("error exercises")
            time.sleep(5)

    getclasshour()
    enterUrl("https://www.2-class.com/api/user/logout")


def getclasshour():
    enterUrl("https://www.2-class.com/api/growth/getMyBank")
    n=0
    while (1):
        n=n+1
        time.sleep(3)
        pyautogui.click(450,300)
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.hotkey('ctrl', 'c')
        text=pyperclip.paste()
        if(n>=5):
            cur.execute(f"UPDATE class_userinfo SET classhour=-2 WHERE (id={userinfo[0]})")
            db.commit()
            return False
        else:
            if(text[0]=="{"):
                log.debug(text)
                j=json.loads(text)
                try:
                    classhour=j['data']['classHour']
                except:
                    classhour=-4
                cur.execute(f"UPDATE class_userinfo SET classhour={classhour} WHERE (id={userinfo[0]})")
                db.commit()
                log.info(f"{userinfo[1]}完成{classhour}学时")
                return classhour
                break
            else:
                enterUrl("https://www.2-class.com/api/growth/getMyBank")
if __name__ == "__main__":
    # getclasshour()
    while(1):
        try:
            if(login()):
                # userinfo=(4124, '陈兴宇', '100班', 'chenxingyu38296', '45851390', '七年级', None, None)
                if(userinfo[5]=="七年级"):
                    courseId=["1593","1594","1606","1531",'1532']
                elif(userinfo[5]=="八年级"):
                    courseId=["1591","1592","1603","1604",'1607',"1529",'1530']
                elif(userinfo[5]=="九年级"):
                    courseId=["1589","1590","1608","1527",'1528']
                classhours(courseId)
                # exercises("1593")
            else:
                time.sleep(3)
        except Exception as e:
            log.error(f"<--- {e} --->")
            
